package com.android.nearshop.app.adapter.listadapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.location.Location;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.guesslike.GuessLikeActivity;
import com.android.nearshop.app.activity.shop.ShopDetailActivity;
import com.android.nearshop.app.widget.LoadableView.IdisplayNetErrAndRefreshView;
import com.android.nearshop.app.widget.PullToRefreshListView;
import com.android.nearshop.app.widget.PullToRefreshListView.OnRefreshListener;
import com.android.nearshop.business.cache.DataCacheManager;
import com.android.nearshop.business.location.MyBMapManager;
import com.android.nearshop.io.protocol.ProtocolManager;
import com.android.nearshop.io.protocol.in.FindShopAction;
import com.android.nearshop.io.protocol.in.SoapAction.ActionListener;
import com.android.nearshop.io.protocol.out.PageInfo;
import com.android.nearshop.io.protocol.out.Shop;
import com.android.nearshop.io.protocol.out.ShopList;
import com.android.nearshop.util.Constant;

/**
 * @File: CommonListAdapter.java
 * @Description: 查询商家列表公用适配器，此包括按序排序以及载入视图等！
 * @Author: denglixia、zhaohua
 * @Date: 2012-8-18 
 * @Copyright : copyrights reserved by personal 2007-2011
 */
public class CommonListAdapter extends LoadableListAdapter<Shop> implements
        OnClickListener,DataLoaderHandler<Shop>
{
    private FindShopAction mFindShopAction;
    private TextView mTotalLabel;
    private Button mDistance;
    private Button mLevel;
    private Button mVisited;
    boolean clickratesDesc = false;
    boolean distanceDesc = true;
    boolean recommendDesc = false;
    private boolean isScrollStateChangedEnble = true;
    
    private OnClickListener mOnItemClick;
    private IdisplayNetErrAndRefreshView mNetView;
    //add by huangyue 当数据加载完成后给外部一个callback
    private Handler mCallback;
    
	private PullToRefreshListView pullListview;
    
    public void setCallback(Handler callback) {
		this.mCallback = callback;
	}
    //end

	public CommonListAdapter(Context context, ListView listView)
    {
        super(context,listView,null);
        
        final Context cxt = context;
        mOnItemClick = new OnClickListener(){
    		@Override
    		public void onClick(View v) {
    			if(v.getTag() instanceof ViewHolder){
	    			ViewHolder vh = (ViewHolder) v.getTag();
	    			if(vh.mShopId > 0){
	    				Intent intent = new Intent();
	    				intent.setClass(cxt.getApplicationContext(), ShopDetailActivity.class);
	    				intent.putExtra(Constant.TAG_DETAIL_SHOPID, vh.mShopId);
	    				intent.putExtra(Constant.TAG_DISCOUNT, vh.mDiscount.getText());
	    				
	    				cxt.startActivity(intent);
	    			}
    			}
    		}
        };
        setDataLoaderHandler(this);
        
        if(listView instanceof PullToRefreshListView)
        {
            pullListview = (PullToRefreshListView)listView;
            pullListview.setOnRefreshListener(new OnRefreshListener()
            {
                @Override
                public void onRefresh()
                {
                    resetPageInfo();
                    reload();
                    loadData();
                }
            });
        }
    }
	
    public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
		if(pullListview != null){
            pullListview.setOnRefreshListener(onRefreshListener);
		}
	}
	
	
	/** 设置网络异常窗口监听者*/
	public void setIdisplayNetErrAndRefreshView(IdisplayNetErrAndRefreshView view)
	{
	    this.mNetView = view;
	}
	
    /**
     * 这个由外部控制,第一次载入时
     * @param action
     * @param loadingView 包含 activity_findshop布局的可以实例话这个对象
     */
    public void setAction(FindShopAction action)
    {
        mFindShopAction = action;
        mFindShopAction.setActionListener(new ActionListener<ShopList>()
                {
                    @Override
                    public void onSucceed(ShopList result)
                    {
                        if (result != null)
                        {
                        	//alter by huangyue 当mPageInfo ！= null时过滤条件修改总数不一样了
//                            if(mPageInfo == null)
//                            {
                                mPageInfo = result.pageInfo;
                                mPageInfo.curPage = mFindShopAction.curPage;
                                mPageInfo.pageNum = mFindShopAction.pageNum;
//                            }
                            //end 
                            onLoaded(result.shopList);
                            if (mTotalLabel != null)
                            {
                                if (mPageInfo != null)
                                {
                                    int areaId = mFindShopAction.getAreaId();
                                    String area = "";
                                    String cateStr = "";
                                    List<Integer> cs = mFindShopAction.getCatalogyIds();
                                    if (areaId > 0)
                                    {
                                        area = DataCacheManager.getInstance().getAreaNameById(areaId) + " ";
                                    } 
                                    if (cs == null || cs.size() == 0)
                                    {
                                        cateStr = mContext.getString(R.string.all_cate);
                                    } else if (cs.size() > 1)
                                    {
                                        cateStr = DataCacheManager.getInstance().getCateNameById(cs.get(0)) + "...";
                                    } else if (cs.size() == 1)
                                    {
                                        cateStr = DataCacheManager.getInstance().getCateNameById(cs.get(0));
                                    }
        
                                    // 显示查询的全部商家数
                                    mTotalLabel.setText(area + cateStr + mContext.getString(R.string.cheap_label,mPageInfo.totalNum + ""));
                                }
                            }
                                                                                   
                            if(mCallback != null){
                            	Message msg = new Message();
                            	msg.what = Constant.HANDLER_SCUCESS;
                            	msg.obj = result;
                            	mCallback.sendMessage(msg);
                            }
                        } else
                        {
                            onLoaded(null);
                        }
                    }

                    @Override
                    public void onError(int resultCode)
                    {
                        if(mPageInfo != null)
                        {
                            mPageInfo.restoreNext();
                        }
                        CommonListAdapter.super.onError();
                    }
                });
    }

    /** 如果需要上面的按钮栏的话，可以设置这个 */
    public void setToolView(View panel)
    {
        mDistance = (Button)panel.findViewById(R.id.distance);
        mLevel = (Button)panel.findViewById(R.id.start_level);
        mVisited = (Button)panel.findViewById(R.id.visit_num);
        
        mDistance.setOnClickListener(this);
        mLevel.setOnClickListener(this);
        mVisited.setOnClickListener(this);
    }

    /** 设置统计标签，如果需要的话 */
    public void setTotalView(TextView total_label)
    {
        this.mTotalLabel = total_label;
    }
    
    private boolean distance = false;      
    private boolean recommend = false;       
    private boolean clickrates = false;

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.distance:
            {
            	if(distance){
            		return;
            	}
            	
                distance = true;
                recommend = false;       
                clickrates = false;
//                distanceDesc = !distanceDesc;
                break;
            }
            case R.id.start_level:
            {
            	if(recommend){
            		return;
            	}
            	
                recommend = true;
                distance = false;      
                clickrates = false;
//                recommendDesc = !recommendDesc;
                break;
            }
            case R.id.visit_num:
            {
            	if(clickrates){
            		return;
            	}
            	
                clickrates = true;
                distance = false;
                recommend = false;       
//                clickratesDesc = !clickratesDesc;
                break;
            }
        }
        
        mDistance.setBackgroundResource(R.drawable.sort_filter_button_normal);
        mLevel.setBackgroundResource(R.drawable.sort_filter_button_normal);
        mVisited.setBackgroundResource(R.drawable.sort_filter_button_normal);
        mDistance.setTextColor(Color.BLACK);
        mLevel.setTextColor(Color.BLACK);
        mVisited.setTextColor(Color.BLACK);
        
        v.setBackgroundResource(R.drawable.sort_filter_button_selected);
        ((Button) v).setTextColor(Color.WHITE);
        
        mFindShopAction.setOrderStruct(distance, false, recommend,
                true, clickrates, true);
        
        resetPageInfo();
        reload();
        loadData();
    }
    
    
    @Override
    public void reload() {
    	super.reload();
    	Location loc = MyBMapManager.getInstace(mContext).getMyGcjLoation();
    	
    	if(loc != null && mFindShopAction != null){
    		mFindShopAction.setLocation(loc.getLongitude(), loc.getLatitude());
    	}
    }
    
    /**
     * 清空分页信息
     */
    public void resetPageInfo()
    {
    	if(mPageInfo != null)
        {
            mPageInfo.reset();
        }
    }
    
    /**
     * 从服务器下载数据
     */
    public void loadData()
    {
        showLoading();
        getNext(this);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ViewHolder viewHolder = null;
        if (convertView == null)
        {
            convertView = inflater.inflate(R.layout.list_item_common, null);
            viewHolder = new ViewHolder();
            viewHolder.mTitle = (TextView) convertView.findViewById(R.id.title);
            viewHolder.mDiscount = (TextView) convertView
                    .findViewById(R.id.discount);
            viewHolder.mSubTitle = (TextView) convertView
                    .findViewById(R.id.subtitle);
            viewHolder.mDistance = (TextView) convertView
                    .findViewById(R.id.distance);
            viewHolder.mRatingBar_Recommend = (RatingBar) convertView
                    .findViewById(R.id.ratingBar_recommend);
            viewHolder.mComment = (TextView) convertView
                    .findViewById(R.id.comment);
            viewHolder.mAddress = (TextView) convertView
                    .findViewById(R.id.address);
            convertView.setTag(viewHolder);
        } else
        {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Resources res = mContext.getResources();
        Shop shop = (Shop) getItem(position);
        setDiscount(viewHolder, res, shop);
        viewHolder.mShopId = shop.shopId;
        viewHolder.mTitle.setText(shop.shopName);

        String category = res.getString(R.string.category_format,
                shop.catalogyName);
        viewHolder.mSubTitle.setText(category);

        setDistance(viewHolder, shop);

        viewHolder.mRatingBar_Recommend.setRating((float) shop.recommend);
        String comment = res.getString(R.string.comment, shop.commCount);
        viewHolder.mComment.setText(comment);
        viewHolder.mAddress.setText(shop.shopAdd);
        convertView.setOnClickListener(mOnItemClick);

        return convertView;
    }

    private void setDistance(ViewHolder viewHolder, Shop shop)
    {
//        double distance = Math.round(shop.posDistance * 100) / 100.0;
    	double distance = Math.round(shop.posDistance / 50)  * 50;
    	
        if (distance > 1000)
        {
            viewHolder.mDistance.setText(distance / 1000 + mContext.getString(R.string.distance_km));
        } else
        {
            viewHolder.mDistance.setText(((int)distance) + mContext.getString(R.string.distance_m));
        }
    }

    private void setDiscount(ViewHolder viewHolder, Resources res, Shop shop)
    {
        if (shop.discount == null)
        {
            viewHolder.mDiscount.setVisibility(View.INVISIBLE);
            return;
        } else
        {
            viewHolder.mDiscount.setVisibility(View.VISIBLE);
        }
        String discount = null;
        try
        {
            Float.parseFloat(shop.discount);
            discount = res.getString(R.string.discount, shop.discount);
        } catch (Exception e)
        {
            discount = shop.discount;
        }

        viewHolder.mDiscount.setText(discount);
    }

    class ViewHolder
    {
    	int mShopId;
        TextView mTitle;
        TextView mDiscount;
        TextView mSubTitle;
        TextView mDistance;
        RatingBar mRatingBar_Recommend;
        TextView mComment;
        TextView mAddress;

        public ViewHolder()
        {}
    }

    // 测试列表用数据
    void testAdapter()
    {
        List<Shop> shoplist = new ArrayList<Shop>();
        for (int i = 0; i < 20; i++)
        {
            Shop shop = new Shop();
            shop.shopName = "稻香酒楼（第一国际店）";
            shop.discount = String.valueOf(i + 1);
            shop.catalogyName = "餐饮美食—自助餐";
            shop.posDistance = 100.0;
            shop.recommend = 3;
            shop.commCount = 60;
            shop.shopAdd = "南城区宏图路高盛科技大厦804";
            shoplist.add(shop);
        }
        setList(shoplist);
    }
    //////////////////////////////////////////////////////////////////////////////////////
    // 分页区域
    private PageInfo mPageInfo;
    @Override
    public int getMaxItems()
    {
        return 100;
    }

    @Override
    public void getNext(final DataLoadedCallback<Shop> callback)
    {
        if(mNetView != null && !MyApplication.getContext().isNetWorkAvailable())
        {
            mNetView.showNoNetworkDialog();
        }else
        {
            if(mPageInfo != null)
            {
                // 只能调用之前设置请求的下一页
                mFindShopAction.setPage(mPageInfo.getNext(), mPageInfo.pageNum);
            }
        	ProtocolManager.getProtocolManager().submitAction(mFindShopAction);
        }
    }
    
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    	if(isScrollStateChangedEnble){
    		super.onScrollStateChanged(view, scrollState);
    	}
    }

    public void setScrollStateChangedEnble(boolean isScrollStateChangedEnble) {
		this.isScrollStateChangedEnble = isScrollStateChangedEnble;
	}

	@Override
    public boolean isLoading()
    {
    	if(mFindShopAction == null){
    		return false;
    	}
        return mFindShopAction.isLoading();
    }

    @Override
    public boolean haveNext()
    {
        return mPageInfo != null ? mPageInfo.hasNext() : true;
    }
}
